<template>
  <div class="gallery-editor">
    <div class="container">
      <el-page-header @back="goBack" title="返回管理后台">
        <template #content>
          <span class="page-title">画廊管理</span>
        </template>
      </el-page-header>
      
      <div class="editor-content">
        <el-row :gutter="20">
          <el-col :xs="24" :lg="16">
            <el-card>
              <template #header>
                <div class="card-header">
                  <h2>{{ isEditing ? '编辑图片' : '添加图片' }}</h2>
                  <el-button type="primary" @click="saveImage" :loading="saving">
                    {{ isEditing ? '更新' : '保存' }}
                  </el-button>
                </div>
              </template>
              
              <el-form :model="imageForm" :rules="formRules" ref="formRef" label-width="100px">
                <el-form-item label="图片标题" prop="title">
                  <el-input v-model="imageForm.title" placeholder="请输入图片标题" />
                </el-form-item>
                
                <el-form-item label="图片URL" prop="url">
                  <el-input v-model="imageForm.url" placeholder="请输入图片URL" />
                  <div class="image-preview" v-if="imageForm.url">
                    <img :src="imageForm.url" alt="预览" />
                  </div>
                </el-form-item>
                
                <el-form-item label="图片描述">
                  <el-input
                    v-model="imageForm.description"
                    type="textarea"
                    :rows="3"
                    placeholder="请输入图片描述（可选）"
                  />
                </el-form-item>
              </el-form>
            </el-card>
          </el-col>
          
          <el-col :xs="24" :lg="8">
            <el-card>
              <template #header>
                <h3>图片列表</h3>
              </template>
              
              <div class="image-list">
                <div 
                  v-for="image in imageList" 
                  :key="image.id"
                  class="image-item"
                  :class="{ active: selectedImage?.id === image.id }"
                  @click="selectImage(image)"
                >
                  <div class="image-thumbnail">
                    <img :src="image.url" :alt="image.title" />
                  </div>
                  <div class="image-info">
                    <h4>{{ image.title }}</h4>
                    <p v-if="image.description">{{ image.description }}</p>
                  </div>
                  <div class="image-actions">
                    <el-button type="primary" size="small" @click.stop="editImage(image)">
                      编辑
                    </el-button>
                    <el-button type="danger" size="small" @click.stop="deleteImage(image.id)">
                      删除
                    </el-button>
                  </div>
                </div>
              </div>
              
              <div class="add-new">
                <el-button type="success" @click="addNewImage" style="width: 100%;">
                  添加新图片
                </el-button>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getGalleryData } from '../../api/serverApi'

export default {
  name: 'GalleryEditor',
  setup() {
    const router = useRouter()
    const formRef = ref()
    const imageList = ref([])
    const selectedImage = ref(null)
    const isEditing = ref(false)
    const saving = ref(false)
    
    const imageForm = ref({
      id: null,
      title: '',
      url: '',
      description: ''
    })
    
    const formRules = {
      title: [
        { required: true, message: '请输入图片标题', trigger: 'blur' }
      ],
      url: [
        { required: true, message: '请输入图片URL', trigger: 'blur' }
      ]
    }
    
    const goBack = () => {
      router.push('/admin')
    }
    
    const loadImages = () => {
      imageList.value = getGalleryData()
    }
    
    const addNewImage = () => {
      isEditing.value = false
      selectedImage.value = null
      imageForm.value = {
        id: Date.now(),
        title: '',
        url: '',
        description: ''
      }
    }
    
    const selectImage = (image) => {
      selectedImage.value = image
    }
    
    const editImage = (image) => {
      isEditing.value = true
      selectedImage.value = image
      imageForm.value = { ...image }
    }
    
    const deleteImage = async (id) => {
      try {
        await ElMessageBox.confirm('确定要删除这张图片吗？', '确认删除', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        imageList.value = imageList.value.filter(item => item.id !== id)
        if (selectedImage.value?.id === id) {
          selectedImage.value = null
          addNewImage()
        }
        
        localStorage.setItem('galleryData', JSON.stringify(imageList.value))
        ElMessage.success('图片删除成功')
      } catch (error) {
        // 用户取消删除
      }
    }
    
    const saveImage = async () => {
      if (!formRef.value) return
      
      try {
        await formRef.value.validate()
        saving.value = true
        
        if (isEditing.value) {
          const index = imageList.value.findIndex(item => item.id === imageForm.value.id)
          if (index !== -1) {
            imageList.value[index] = { ...imageForm.value }
          }
          ElMessage.success('图片更新成功')
        } else {
          imageList.value.unshift({ ...imageForm.value })
          ElMessage.success('图片添加成功')
        }
        
        localStorage.setItem('galleryData', JSON.stringify(imageList.value))
        addNewImage()
      } catch (error) {
        console.error('保存失败:', error)
      } finally {
        saving.value = false
      }
    }
    
    onMounted(() => {
      loadImages()
      addNewImage()
    })
    
    return {
      formRef,
      imageList,
      selectedImage,
      isEditing,
      saving,
      imageForm,
      formRules,
      goBack,
      addNewImage,
      selectImage,
      editImage,
      deleteImage,
      saveImage
    }
  }
}
</script>

<style scoped>
.gallery-editor {
  padding: 20px 0;
}

.page-title {
  font-size: 1.5rem;
  font-weight: bold;
  color: #4CAF50;
}

.editor-content {
  margin-top: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  color: #4CAF50;
  margin: 0;
}

.image-preview {
  margin-top: 10px;
  text-align: center;
}

.image-preview img {
  max-width: 300px;
  max-height: 200px;
  border-radius: 4px;
  border: 1px solid #ddd;
}

.image-list {
  max-height: 400px;
  overflow-y: auto;
}

.image-item {
  display: flex;
  align-items: center;
  gap: 15px;
  padding: 15px;
  border: 1px solid #eee;
  border-radius: 8px;
  margin-bottom: 10px;
  cursor: pointer;
  transition: all 0.3s;
}

.image-item:hover {
  border-color: #4CAF50;
  background: #f9f9f9;
}

.image-item.active {
  border-color: #4CAF50;
  background: #e8f5e8;
}

.image-thumbnail {
  flex-shrink: 0;
}

.image-thumbnail img {
  width: 60px;
  height: 60px;
  object-fit: cover;
  border-radius: 4px;
  border: 1px solid #ddd;
}

.image-info {
  flex: 1;
}

.image-info h4 {
  margin: 0 0 5px 0;
  color: #333;
  font-size: 1rem;
}

.image-info p {
  margin: 0;
  color: #666;
  font-size: 0.9rem;
  line-height: 1.4;
}

.image-actions {
  display: flex;
  gap: 5px;
}

.add-new {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #eee;
}

@media (max-width: 768px) {
  .card-header {
    flex-direction: column;
    gap: 15px;
  }
  
  .image-item {
    flex-direction: column;
    text-align: center;
    gap: 10px;
  }
  
  .image-actions {
    justify-content: center;
  }
}
</style> 